<template>
  <div>
    <el-dialog v-model="props.publicDialog" :title="title" @close="handleClose" width="550px">
      <el-form ref="procurementRef" :model="procurementForm" :rules="rules" label-position="left" label-width="auto"
        v-if="props.showIndex === 1 || props.showIndex === 0">
        <el-form-item label="是否需要采购" prop="needProcure" required>
          <el-switch v-model="procurementForm.needProcure" :active-value="true" :inactive-value="false" active-text="开启"
            inactive-text="关闭" inline-prompt @change="handleProcurement" />
        </el-form-item>

        <el-form-item label="是否一键代发" prop="needOneClickShipment" required>
          <el-switch v-model="procurementForm.needOneClickShipment" :active-value="true" :inactive-value="false"
            active-text="开启" inactive-text="关闭" inline-prompt :disabled="globalDisabled" />
        </el-form-item>
        <el-form-item label="采购地址" prop="replaceUrl" :required="!globalDisabled">
          <!-- 新商品源-->
          <el-input v-model.trim="procurementForm.replaceUrl" :disabled="globalDisabled" />
        </el-form-item>
        <el-form-item label="采购订单号" prop="procureCode" :required="!globalDisabled">
          <el-input v-model="procurementForm.procureCode" :disabled="globalDisabled" />
        </el-form-item>
        <el-form-item label="采购数量" prop="procureCount" required>
          <el-input-number :min="0" style="width: 100%" v-model="procurementForm.procureCount"
            :disabled="globalDisabled" />
        </el-form-item>
        <el-form-item label="采购货币" prop="currencyId" :required="!globalDisabled">
          <el-select v-model="procurementForm.currencyId" placeholder="请选择" :disabled="globalDisabled">
            <el-option v-for="dict in sys_currency_code" :key="dict.id" :label="dict.description"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="采购价格" prop="procurePrice" required>
          <el-input-number :precision="2" :min="0" style="width: 100%" v-model="procurementForm.procurePrice"
            :disabled="globalDisabled" />
        </el-form-item>
        <!-- 运费价格-->
        <el-form-item label="采购运费" prop="freightAmount" required>
          <el-input-number :precision="2" :min="0" style="width: 100%" type="number"
            v-model="procurementForm.freightAmount" :disabled="globalDisabled" />
        </el-form-item>
        <el-form-item label="采购物流" prop="transportId" :required="!globalDisabled">
          <el-select v-model="procurementForm.transportId" placeholder="请选择" :disabled="globalDisabled">
            <el-option v-for="dict in sys_recursive" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="物流单号" prop="logisticsCode">
          <el-input v-model.trim="procurementForm.logisticsCode" :disabled="globalDisabled" />
        </el-form-item>
        <el-form-item label="采购备注" prop="auditRemark">
          <el-input v-model.trim="procurementForm.remark" type="textarea" :rows="5" maxlength="300" show-word-limit
            placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <el-form ref="deliveryRef" :model="deliveryForm" :rules="rules" label-position="left"
        v-if="props.showIndex === 3">
        <el-form-item label="物流名称" prop="transportId" required>
          <el-select v-model="deliveryForm.transportId" placeholder="请选择" @change="changeMode">
            <el-option v-for="dict in sys_recursive" :key="dict.id" :label="dict.name" :value="dict.id"
              :disabled="!dict.status"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运单单号" prop="freightCode" required>
          <el-input v-model.trim="deliveryForm.freightCode" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="物流运费" prop="freightAmount" required>
          <el-input-number v-model="deliveryForm.freightAmount" placeholder="请输入" style="width: 100%" :min="0" />
        </el-form-item>
        <el-form-item label="物流备注" prop="remark">
          <el-input v-model.trim="deliveryForm.remark" type="textarea" :rows="5" maxlength="300" show-word-limit
            placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div v-if="props.showIndex !== 0">
          <el-button type="primary" @click="submitForm">确 定 </el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch, reactive } from "vue";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["handleClose", "handleSure"]);
const sys_currency_code = ref([]); //货币
const sys_recursive = ref([]); //快递
const title = ref("采购");
const procurementForm = ref({
  id: null, // 采购记录id
  orderProductLineId: null, // 订单商品id
  needProcure: true, //是否需要采购
  replaceUrl: "", // 新商品源
  currencyId: null, //货币
  needOneClickShipment: false, // 是否一键代发
  procurePrice: null, // 采购价
  procureCount: null, // 采购数量
  freightAmount: null, // 运费
  procureCode: "", // 采购单号
  logisticsCode: "", // 物流单号
  transportId: null,//采购物流
  remark: "", // 备注
}); //采购参数
const deliveryForm = ref({
  orderId: null, //订单id
  transportId: null, //货运方式
  freightCode: "", //运单号
  freightAmount: null, //运费
  remark: "", //备注
}); //发货

const globalDisabled = ref(false); //全局禁用，当不需要采购的时候，紧张选项和输入

const props = defineProps({
  // 判断类型：true：新增，false是编辑
  publicDialog: {
    type: Boolean,
    default: false,
  },
  showIndex: {
    type: Number,
    default: 1, //1是采购，0是查看，3是发货
  },
  publicItem: {
    type: Object,
    default: {},
  },
  id: {
    type: Number || String,
    default: null,
  },
});
watch(
  () => props.publicDialog,
  () => {
    if (!props.publicDialog) return;
    if (props.showIndex === 1) {
      productAssignment();
      title.value = "采购";
    } else if (props.showIndex === 3) {
      title.value = "发货";
    } else {
      title.value = "采购";
      productAssignment();
    }

    console.log(props.showIndex, "新的值:");
  }
);
onMounted(() => {
  getRecursive();

});
const submitForm = () => {
  console.log(procurementForm.value);
  // return
  if (props.showIndex === 1) {
    proxy.$refs["procurementRef"].validate((valid) => {
      if (!valid) return;
      if (
        procurementForm.value.needProcure &&
        !procurementForm.value.procureCount
      )
        return proxy.$modal.msgError("采购数量不能为0");
      order.order
        .orderAddorupdateprocure({
          data: procurementForm.value,
        })
        .then((res) => {
          if (res.code !== 200) return;
          stagnation()
          proxy.$modal.msgSuccess(res.message);
          emits("handleSure");

        });
    });
  } else if (props.showIndex === 3) {
    // order.order.orderDelivery({
    //   data: {
    //     orderId: 0,
    //     transportId: 0,
    //     freightCode: '',
    //     freightAmount: 0
    //   }
    // }).then((res) => {
    // });
    proxy.$refs["deliveryRef"].validate((valid) => {
      if (!valid) return;
      deliveryForm.value.orderId = props.publicItem.id;
      order.order
        .orderDelivery({
          data: deliveryForm.value,
        })
        .then((res) => {
          if (res.code !== 200) return;
          stagnation()
          emits("handleSure");
          proxy.$modal.msgSuccess(res.message);

        });
    });
  }
};

// 是否需要采购
const handleProcurement = (e) => {
  if (e) {
    globalDisabled.value = false;
  } else {
    globalDisabled.value = true;
    procurementForm.value.replaceUrl = ""; //  新商品源
    procurementForm.value.needOneClickShipment = false; // 是否一键代发
    procurementForm.value.procureCode = ""; // 采购单号
    procurementForm.value.logisticsCode = ""; // 物流单号

    procurementForm.value.procurePrice = 0; //  采购价
    procurementForm.value.procureCount = 0; // 采购数量
    procurementForm.value.freightAmount = 0; // 运费
    procurementForm.value.currencyId = null; // 货币
  }
};


// 选择快递，快递费用赋值给发货的费用
const changeMode = (e) => {
  deliveryForm.value.freightAmount = sys_recursive.value.find(
    (code) => code.id === e
  ).amount;
};
// 获取快递
const getRecursive = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    params: {},
  }
  // 获取货币
  product.currency.currencyList().then((res) => {
    sys_currency_code.value = res.data;
  });
  // 快递管理
  site.general
    .sitetransportList({
      data: from,
    })
    .then((res) => {
      sys_recursive.value = res.data;
    });
};
// 赋值订单商品id（orderProductLineId）
const productAssignment = () => {
  procurementForm.value.orderProductLineId =
    props.publicItem.orderProductLineId;
  if (props.publicItem.procureStatus === "wait_procure") return;
  order.order
    .orderGetprocure({
      pathParams: {
        orderProductLineId: props.publicItem.orderProductLineId,
      },
    })
    .then((res) => {
      console.log(res.data);
      procurementForm.value.id = res.data?.id;
      if (!res.data.needProcure) {
        globalDisabled.value = true;
      } else {
        globalDisabled.value = false;
      }
      procurementForm.value.remark = res.data.remark;
      procurementForm.value.needProcure = res.data.needProcure; //是否需要采购
      procurementForm.value.replaceUrl = res.data.replaceUrl; //新商品源
      procurementForm.value.needOneClickShipment =
        res.data.needOneClickShipment; // 是否一键代发
      procurementForm.value.transportId = res.data.transportId; //采购物流

      procurementForm.value.procurePrice = res.data.procurePrice; //  采购价
      procurementForm.value.procureCount = res.data.procureCount; // 采购数量
      procurementForm.value.freightAmount = res.data.freightAmount; // 运费
      procurementForm.value.logisticsCode = res.data.logisticsCode; // 物流单号
      procurementForm.value.procureCode = res.data.procureCode; // 采购单号
      procurementForm.value.currencyId = res.data.currencyId; // 货币

      // console.log(res.data, "采购详情");
    });
};
const rules = reactive({
  replaceUrl: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern: /^https?:\/\/.+/,
      message: "请输入正确的url",
      trigger: "blur",
    },
  ],
  procurePrice: [{ required: true, message: "请输入", trigger: "blur" }],
  transportId: [{ required: true, message: "请选择", trigger: "blur" }],
  procureCount: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "请输入正确数量",
      trigger: "blur",
    },
  ],
  procureCode: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern: /^[A-Za-z0-9]+$/,
      message: "请输入正确的采购单号",
      trigger: "blur",
    },
  ],
  logisticsCode: [
    {
      pattern: /^[A-Za-z0-9]+$/,
      message: "请输入正确的物流单号",
      trigger: "blur",
    },
  ],
  currencyId: [{ required: true, message: "请选择", trigger: "blur" }],
  // 发货
  transportId: [{ required: true, message: "请选择", trigger: "blur" }],
  freightCode: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern: /^[A-Za-z0-9]+$/,
      message: "请输入正确的运单号码",
      trigger: "blur",
    },
  ],
  freightAmount: [{ required: true, message: "请输入", trigger: "blur" }],
});
const handleClose = () => {
  stagnation()
  emits("handleClose");
};
const stagnation = () => {
  globalDisabled.value = false;
  procurementForm.value.id = null
  procurementForm.value.orderProductLineId = null
  procurementForm.value.needProcure = true
  procurementForm.value.replaceUrl = ''
  procurementForm.value.currencyId = null
  procurementForm.value.needOneClickShipment = null
  procurementForm.value.procurePrice = null
  procurementForm.value.procureCount = null
  procurementForm.value.freightAmount = null
  procurementForm.value.procureCode = ''
  procurementForm.value.logisticsCode = ''
  procurementForm.value.transportId = null
  procurementForm.value.remark = ''
  proxy.resetForm("procurementRef");
  proxy.resetForm("deliveryRef");
}
</script>